package com.sharing.library.controller;

import com.sharing.library.entity.File;
import com.sharing.library.service.FileService;
import com.zhx.framework.util.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author zhanghaixuan
 * @create 2018/3/19-上午10:06
 **/
@RestController
@RequestMapping("/file")
@Api(description="文件上传")
public class FileController {
    @Autowired
    private FileService fileService;

    /**
     * 保存
     */
    @PostMapping("/upload")
    @ApiOperation(value="上传文件 返回文件ID", notes="上传文件 返回文件ID")
    public Result upload(@RequestParam("file") MultipartFile file,
                         HttpServletRequest request) {
        String contentType = file.getContentType();
        String fileName = file.getOriginalFilename();

        try {
            Long upload = fileService.upload(input2byte(file.getInputStream()), fileName, file.getSize(), contentType);

            return Result.OK("",upload);

        } catch (Exception e) {
            // TODO: handle exception
            return Result.Error(501,e.getMessage());
        }
    }

    /**
     * 获取
     */
    @GetMapping("/download")
    @ApiOperation(value="下载文件 流形式", notes="下载文件 流形式")
    public void download(@RequestParam Long filId,HttpServletResponse response){
        File download = fileService.download(filId);

        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        response.setHeader("Content-Disposition", "attachment;filename=" + download.getFileName());

        byte[] bytes = download.getIostream();

        try {
            for (int i = 0; i < bytes.length; ++i) {
                if (bytes[i] < 0) {// 调整异常数据
                    bytes[i] += 256;
                }
            }
            ServletOutputStream out = response.getOutputStream();
            out.write(bytes);
            out.flush();
            out.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 将 流 转换为byte
     * @param inStream
     * @return
     * @throws IOException
     */
    public static final byte[] input2byte(InputStream inStream) throws IOException {
        ByteArrayOutputStream swapStream = null;
        try {
            swapStream = new ByteArrayOutputStream();
            byte[] buff = new byte[1024];
            int rc = 0;
            while ((rc = inStream.read(buff, 0, 1024)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            return swapStream.toByteArray();
        } catch (Exception e) {
            System.out.println(e.getMessage());
        } finally {
            if (swapStream != null) {
                swapStream.close();
            }
        }
        return null;
    }
}
